package com.elegantmall.config;


import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

@Aspect
@Component
public class NeedAuthConfig {

    @Pointcut("@annotation(com.elegantmall.annotation.NeedAuth)")
    public void needAuth(){

    }

    @Before("needAuth()")
    public void BeforeRequestInDirect(JoinPoint point) throws IOException {
        if(StpUtil.getLoginIdDefaultNull()==null){
            HttpServletResponse response=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            ServletOutputStream writer = response.getOutputStream();
            response.setContentType("application/json;charset=utf-8");//解决前台乱码问题
            writer.println("need auth");
            writer.close();
        }
    }
}
